<script setup lang="ts">
import { Button } from "@/components/Button";
import metaidv2Utils from "@/utils/metaidv2Utils";
import { Form, FormItem, message, Upload, UploadProps } from "ant-design-vue";
import {
computed,
onBeforeUnmount,
onMounted,
reactive,
ref,
watch
} from "vue";

const props = defineProps({
  showFee: {
    type: Boolean,
    default: false,
  },
  isPayComment: {
    type: Boolean,
    default: false,
  },
  isPayForward: {
    type: Boolean,
    default: false,
  },
  quotePin: {
    type: Object,
    required: false,
  },
});

const emit = defineEmits(["close", "newBuzzSuccess"]);

const form = reactive({
  content: "",
});
const isMobile = ref(false);
const sureBtnLoading = ref(false);
const newBuzzForm: any = ref(null);
const fileList = ref();

// Computed properties
const title = computed(() => {
  if (props.isPayComment) {
    if (!props.quotePin) {
      message.error("param error");
    }
    return "Comment Buzz";
  }
  if (props.isPayForward) {
    if (!props.quotePin) {
      message.error("param error");
    }
    return "Forward Buzz";
  }
  return "New Buzz";
});

// Watchers
watch(isMobile, (newVal) => {
  if (newVal) {
    // Mobile-specific logic here
  } else {
    // Desktop-specific logic here
  }
});

// Lifecycle hooks
onMounted(() => {
  window.addEventListener("resize", handleResize);
  handleResize();
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});

// Methods
const closeWindow = () => {
  emit("close");
};

const handleResize = () => {
  isMobile.value = window.innerWidth <= 768;
};

const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  fileList.value = [...(fileList.value || []), file];
  return false;
};

const handleRemove: UploadProps["onRemove"] = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

const imageTxs = async () => {
  let fileTransactions = [];
  const finalAttachMetafileUri: any = [];
  for (let i = 0; i < fileList.value.length; i++) {
    const current = fileList.value[i];
    // Assuming metaidv2Utils and $walletUtils are globally available or imported
    const compressed = await metaidv2Utils.compressImage(current.originFileObj);
    const fileResult = await metaidv2Utils.fileToAttachment(
      current.type === "image/gif" ? current.originFileObj : compressed
    );
    let opReturnFieldList = [
      Buffer.from("metaid"),
      Buffer.from("create"),
      Buffer.from("/file"),
      Buffer.from("0"),
      Buffer.from("1.0.0"),
      Buffer.from(`${fileResult.fileType};binary`),
      Buffer.from(Buffer.from(fileResult.data, "hex")),
    ];
    const { transactions } = await window.$walletUtils.createPin(
      opReturnFieldList,
      {
        serialAction: "combo",
        transactions: fileTransactions,
      }
    );
    if (!transactions) {
      throw new Error("upload image file failed");
    }
    finalAttachMetafileUri.push(
      "metafile://" +
        transactions[transactions.length - 1].txComposer.getTxId() +
        "i0"
    );
    fileTransactions = transactions;
  }
  return {
    transactions: fileTransactions,
    attachments: finalAttachMetafileUri,
  };
};

const handleSubmit = async () => {
  sureBtnLoading.value = true;
  // 获取名称为newBuzzForm的refs
  await newBuzzForm.value
    .validateFields()
    .then(async (valid) => {
      if (valid) {
        let options: any = {
          content: form.content,
        };
        const imageRes = await imageTxs();
        options.transactions = imageRes.transactions;
        options.attachments = imageRes.attachments;
        if (props.isPayForward) {
          options.quotePin = props.quotePin?.id;
        }
        let res = null;
        if (props.isPayComment) {
          options.commentTo = props.quotePin?.id;
          try {
            console.log("handleSubmit", options);
            res = await window.$walletUtils.payComment(options);
          } catch (error) {
            sureBtnLoading.value = false;
            message.error("Error comment Buzz:" + error);
            return;
          }
        } else {
          try {
            console.log("handleSubmit", options);
            res = await window.$walletUtils.shareToBuzz(options);
          } catch (error) {
            sureBtnLoading.value = false;
            console.log("handleSubmit *** Error", error);
            return;
          }
        }
        sureBtnLoading.value = false;
        if (res) {
          newBuzzForm.value.resetFields();
          emit("newBuzzSuccess");
        }
      } else {
        sureBtnLoading.value = false;
      }
    })
    .catch((error) => {
      console.log("handleSubmit *** catch", error);
      sureBtnLoading.value = false;
    });
};
</script>
 
<template>
  <div>
    <div class="buzz-window" :class="{ 'is-mobile': isMobile }">
      <header class="buzz-header">
        <h1>{{ title }}</h1>
        <i
          class="iconfont icon-guanbi"
          @click="closeWindow"
          style="font-size: 30px; cursor: pointer"
        ></i>
      </header>
      <Form class="buzz-form" :model="form" ref="newBuzzForm">
        <div>
          <FormItem
            name="content"
            class="enter-x"
            :rules="[{ required: true, message: 'Please input your Buzz!' }]"
          >
            <textarea
              id="buzzTextArea"
              placeholder="please input content"
              v-model="form.content"
              name="post"
              cols="30"
              rows="10"
            />
          </FormItem>
        </div>
        <Upload
          v-model:file-list="fileList"
          list-type="picture"
          :before-upload="beforeUpload"
          @remove="handleRemove"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            Select Image(s)
          </a-button>
        </Upload>
        <!-- <div style="overflow: hidden">
          <label class="select-image" for="image-input">Select Image(s)</label>
        </div> -->
        <input id="image-input" type="file" multiple hidden />
        <section class="fee-rate-section" v-if="showFee">
          <div class="rate-left">
            <div class="title">Fee Rate:</div>
            <div class="rate-input-wrap">
              <input type="text" class="_input" />
              <span class="unit">sat/vB</span>
            </div>
          </div>
          <!-- <div class="rate-right">
            <div
              v-for="(rate, index) in feeRates"
              :key="index"
              class="rate-option"
            >
              <div class="value">
                {{ rate.name }}
              </div>
              <div class="label" :for="`rate-option-${index}`">
                {{ rate.value }} sat/vB
              </div>
            </div>
          </div> -->
        </section>
        <footer class="buzz-footer">
          <Button
            type="submit"
            :loading="sureBtnLoading"
            class="btn"
            @click="handleSubmit"
            >Post</Button
          >
        </footer>
      </Form>
    </div>
    <div class="model-wrap" @click="closeWindow"></div>
    <!-- <msgPost
      v-if="buzzDetail.id"
      isComment
      :pinInfo="buzzDetail"
      @showBuzzDetail="showBuzzDetail"
    ></msgPost> -->
  </div>
</template>

<style lang="less" scoped>
.buzz-window {
  position: fixed;
  top: 0;
  top: 50%;
  left: 0;
  left: 50%;
  z-index: 999;
  width: 600px;
  overflow: hidden;
  background-color: #fff;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  border-radius: 20px;
  // 页面居中
  transform: translate(-50%, -50%);
}

.buzz-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  color: #333;
  background-color: #fff;

  h1 {
    flex: 1;
    color: #00b1ff;
    text-align: center;
  }

  .btn-wrap {
    font-size: 26px;
    color: #333;
    background: transparent;
    border: none;
    outline: none;
  }
}

.buzz-form {
  width: 100%;
  padding: 12px;
  background-color: white;
  background-color: #fff;

  /* stylelint-disable-next-line selector-id-pattern */
  #buzzTextArea {
    width: 100%;
    height: 150px;
    padding: 10px;
    color: #333;
    background: #f2f2f2;
    border: none;
    border-radius: 12px;
    outline: none;
  }
}

.rate-option {
  display: flex;
  flex: 1;
  margin-right: 1rem;

  .value {
    margin-right: 20px;
    color: #fff;
  }

  .label {
    color: #00b1ff;
  }
}

.buzz-footer {
  display: flex;
  justify-content: center;
  padding: 10px 0 5px;

  .btn {
    width: 100%;
    color: #fff;
    background: #00b1ff;
    border: none;
    border-radius: 12px;
    outline: none;
  }
}

.is-mobile {
  width: 100%;
  height: 100%;
}

.is-mobile .buzz-form {
  padding: 0.5rem;
}

.fee-rate-section {
  display: flex;
  padding: 20px;
  margin-top: 10px;
  border: 1px solid #00b1ff;
  border-radius: 12px;

  .rate-left {
    flex: 1;

    .title {
      margin-bottom: 20px;
      font-size: 16px;
      color: #fff;
    }

    .rate-input-wrap {
      display: flex;
      align-items: center;

      ._input {
        width: 140px;
        padding: 10px;
        color: #00b1ff;
        border: 1px solid #00b1ff;
        border-radius: 12px;
      }

      .unit {
        margin-left: 10px;
        color: #00b1ff;
      }
    }
  }
}

.model-wrap {
  position: fixed;
  inset: 0;
  z-index: 998;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.7;
}

.select-image {
  display: block;
  float: right;
  padding: 5px;
  margin-top: 5px;
  font-size: 12px;
  line-height: 1;
  color: #333;
  border: 1px solid #333;
  border-radius: 10px;
}
</style>
